import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WorkspaceMember } from '../../entities/workspace-member.entity';
import { CreateWorkspaceMemberDto } from './dto/create-workspace-member.dto';
import { UpdateWorkspaceMemberDto } from './dto/update-workspace-member.dto';
import { UserStatus, WorkspaceMemberRole } from '../../types/enums';
import { User } from '../../entities/user.entity';
import { Workspace } from '../../entities/workspace.entity';

@Injectable()
export class WorkspaceMemberService {
  constructor(
    @InjectRepository(WorkspaceMember)
    private workspaceMemberRepository: Repository<WorkspaceMember>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Workspace)
    private workspaceRepository: Repository<Workspace>,
  ) {}

  async create(
    workspaceId: string,
    createWorkspaceMemberDto: CreateWorkspaceMemberDto,
  ): Promise<WorkspaceMember> {
    // 检查工作区是否存在
    const workspace = await this.workspaceRepository.findOne({
      where: { id: workspaceId },
    });

    if (!workspace) {
      throw new NotFoundException(`工作区 ${workspaceId} 不存在`);
    }

    // 检查用户是否存在
    const user = await this.userRepository.findOne({
      where: { id: createWorkspaceMemberDto.userId },
    });

    if (!user) {
      throw new NotFoundException(`用户 ${createWorkspaceMemberDto.userId} 不存在`);
    }

    // 检查是否已经是成员
    const existingMember = await this.workspaceMemberRepository.findOne({
      where: { 
        workspaceId,
        userId: createWorkspaceMemberDto.userId, 
      },
    });

    if (existingMember) {
      throw new ConflictException(`用户 ${createWorkspaceMemberDto.userId} 已经是工作区成员`);
    }

    // 创建工作区成员
    const workspaceMember = this.workspaceMemberRepository.create({
      workspaceId,
      userId: createWorkspaceMemberDto.userId,
      role: createWorkspaceMemberDto.role || WorkspaceMemberRole.MEMBER,
      joinedAt: new Date(),
      status: UserStatus.ACTIVE,
    });

    return this.workspaceMemberRepository.save(workspaceMember);
  }

  async findAll(workspaceId: string): Promise<WorkspaceMember[]> {
    // 检查工作区是否存在
    const workspace = await this.workspaceRepository.findOne({
      where: { id: workspaceId },
    });

    if (!workspace) {
      throw new NotFoundException(`工作区 ${workspaceId} 不存在`);
    }

    // 查找所有工作区成员
    return this.workspaceMemberRepository.find({
      where: { workspaceId },
      relations: ['user'],
    });
  }

  async findOne(workspaceId: string, id: string): Promise<WorkspaceMember> {
    const workspaceMember = await this.workspaceMemberRepository.findOne({
      where: { id, workspaceId },
      relations: ['user'],
    });

    if (!workspaceMember) {
      throw new NotFoundException(`工作区成员 ${id} 不存在`);
    }

    return workspaceMember;
  }

  async update(
    workspaceId: string,
    id: string,
    updateWorkspaceMemberDto: UpdateWorkspaceMemberDto,
  ): Promise<WorkspaceMember> {
    const workspaceMember = await this.findOne(workspaceId, id);

    // 更新角色
    if (updateWorkspaceMemberDto.role !== undefined) {
      workspaceMember.role = updateWorkspaceMemberDto.role;
    }

    // 更新状态
    if (updateWorkspaceMemberDto.status !== undefined) {
      workspaceMember.status = updateWorkspaceMemberDto.status;
    }

    return this.workspaceMemberRepository.save(workspaceMember);
  }

  async remove(workspaceId: string, id: string): Promise<void> {
    const workspaceMember = await this.findOne(workspaceId, id);
    await this.workspaceMemberRepository.remove(workspaceMember);
  }

  async isWorkspaceMember(workspaceId: string, userId: string): Promise<boolean> {
    const count = await this.workspaceMemberRepository.count({
      where: { 
        workspaceId, 
        userId,
        status: UserStatus.ACTIVE 
      },
    });
    
    return count > 0;
  }

  async getWorkspaceMemberRole(workspaceId: string, userId: string): Promise<WorkspaceMemberRole | null> {
    const member = await this.workspaceMemberRepository.findOne({
      where: { 
        workspaceId, 
        userId,
        status: UserStatus.ACTIVE 
      },
    });
    
    return member ? member.role : null;
  }
} 